package jiuxing

import (
	"bytes"
	"encoding/binary"
	"encoding/hex"
	"fmt"
	"time"

	"github.com/axgle/mahonia"
	"github.com/zeromicro/go-zero/core/logx"
)

type Package struct {
	Cmd        uint8
	Sn         []uint8 //桩号
	Encryption uint8
	PackageLen uint16
	Payload    []uint8
	Check      uint8
}

func GetNowTime() []byte {
	ret := make([]byte, 6)
	now := time.Now()
	ret = append(ret, byte(now.Year()-2000))
	ret = append(ret, byte(now.Month()))
	ret = append(ret, byte(now.Day()))
	ret = append(ret, byte(now.Hour()))
	ret = append(ret, byte(now.Month()))
	ret = append(ret, byte(now.Day()))
	return ret
}
func GetTimeStr(b []byte) string {
	return fmt.Sprintf("20%02d-%02d-%02d %02d:%02d:%02d",
		b[0], b[1], b[2], b[3], b[4], b[5])
}

func GetTimeStamp(b []byte) int64 {
	var LOC, _ = time.LoadLocation("Asia/Shanghai")
	timeFormatStr := "2006-01-02 15:04:05"
	timeStr := GetTimeStr(b)
	logx.Info(timeStr)
	tm, _ := time.ParseInLocation(timeFormatStr, timeStr, LOC)
	return tm.Unix()
}

func GetGbkString(b []byte) string {
	enc := mahonia.NewDecoder("GBK")
	output := enc.ConvertString(string(b))
	return output
}

func GetBcdString(b []byte) string {
	return hex.EncodeToString(b)
}

func GetVersion(b []byte) string {
	return GetBcdString(b[22:23]) + "." + GetBcdString(b[23:24])
}

func String2ByteWithlen(s string, l int) []byte {
	ret := []byte(s)
	if l < len(ret) {
		return ret[:l]
	}
	for i := len(ret); i < l; i++ {
		ret = append(ret, 0)
	}
	return ret
}

func Byte2ByteWithlen(b []byte, l int) []byte {
	ret := b
	if l < len(ret) {
		return ret[:l]
	}
	for i := len(ret); i < l; i++ {
		ret = append(ret, 0)
	}
	return ret
}

func IntToBytes(n int) []byte {
	x := int32(n)
	bytesBuffer := bytes.NewBuffer([]byte{})
	binary.Write(bytesBuffer, binary.LittleEndian, x)
	return bytesBuffer.Bytes()
}

func IntLittleToBytes(n int) []byte {
	x := int32(n)
	bytesBuffer := bytes.NewBuffer([]byte{})
	binary.Write(bytesBuffer, binary.LittleEndian, x)
	return bytesBuffer.Bytes()
}

func Int16ToBytes(i int16) []byte {
	buf := make([]byte, 2)
	binary.BigEndian.PutUint16(buf, uint16(i))
	return buf
}
